<template>
  <div class="dish-management">
    <!-- 搜索和筛选区域 -->
    <div class="search-bar">
      <div class="search-left">
        <el-input
            v-model="searchQuery"
            placeholder="请输入菜品名称"
            clearable
            style="width: 240px; margin-right: 15px"
            @clear="handleSearch"
            @keyup.enter="handleSearch"
        >
          <template #append>
            <el-button :icon="Search" @click="handleSearch" />
          </template>
        </el-input>

        <el-select
            v-model="selectedCategory"
            placeholder="选择菜品分类"
            clearable
            style="width: 180px"
            @change="handleCategoryChange"
        >
          <el-option
              v-for="category in dishCategories"
              :key="category.id"
              :label="category.name"
              :value="category.id"
          />
        </el-select>
      </div>

      <div class="search-right">
        <el-button type="danger" :disabled="!selectedDishes.length" @click="batchDelete">
          批量删除
        </el-button>
        <el-button
            type="success"
            :disabled="!selectedDishes.length"
            @click="batchUpdateStatus(1)"
        >
          批量起售
        </el-button>
        <el-button
            type="warning"
            :disabled="!selectedDishes.length"
            @click="batchUpdateStatus(0)"
        >
          批量停售
        </el-button>
        <el-button type="primary" @click="navigateToAddDish">
          <el-icon><Plus /></el-icon>新建菜品
        </el-button>
      </div>
    </div>

    <!-- 菜品表格 -->
    <el-table
        :data="dishList"
        v-loading="loading"
        border
        stripe
        style="width: 100%"
        @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column prop="name" label="菜品名称" width="200" align="center" />
      <el-table-column label="菜品图片" width="150" align="center">
        <template #default="{ row }">
          <el-image
              style="width: 80px; height: 80px"
              :src="getFullImageUrl(row.image)"
              :preview-src-list="[getFullImageUrl(row.image)]"
              fit="cover"
              preview-teleported
              hide-on-click-modal
          />
        </template>
      </el-table-column>
      <el-table-column prop="categoryName" label="菜品分类" width="200" align="center" />
      <el-table-column prop="price" label="售价(元)" width="150" align="center">
        <template #default="{ row }">
          {{ row.price.toFixed(2) }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="售卖状态" width="100" align="center">
        <template #default="{ row }">
          <el-tag :type="row.status === 1 ? 'success' : 'danger'">
            {{ row.status === 1 ? '在售' : '停售' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="updateTime" label="最后操作时间" width="200" align="center" />
      <el-table-column label="操作" width="220" align="center">
        <template #default="{ row }">
          <el-button size="small" @click="navigateToEditDish(row.id)">修改</el-button>
          <el-button
              size="small"
              :type="row.status === 1 ? 'warning' : 'success'"
              @click="toggleStatus(row)"
          >
            {{ row.status === 1 ? '停售' : '起售' }}
          </el-button>
          <el-button size="small" type="danger" @click="handleDelete(row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页控件 -->
    <Pagination
        :currentPage="currentPage"
        :pageSize="pageSize"
        :total="total"
        @update:currentPage="handlePageChange"
        @update:pageSize="handlePageSizeChange"
    />
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { Search, Plus } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import Pagination from "@/components/common/Pagination.vue";
import {getCategoryByType} from "@/api/category";
import {deleteDishById, deleteDishes, getDishList, updateBatchStatus} from "@/api/dish";
import {fileViewPath} from "@/utils/file";

const router = useRouter()
const loading = ref(false) // 加载状态
// 数据状态
const dishCategories = ref([])
const selectedCategory = ref('')
const searchQuery = ref('')
const dishList = ref([])
const selectedDishes = ref([])

//分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

//图访问路径
const getFullImageUrl = (imagePath) => {
  if (!imagePath) return ''
  return `${fileViewPath}${formatImagePath(imagePath)}`
}

// 加载菜品分类
const loadDishCategories = async () => {
  try {
    const res = await getCategoryByType(1)
    if (res.code === '200') {
      dishCategories.value = res.data
    }else{
      ElMessage.error('获取菜品分类失败')
    }
  } catch (error) {
    ElMessage.error('获取菜品分类失败')
  }
}

// 路径格式化函数（处理Windows路径）
const formatImagePath = (path) => {
  if (!path) return '';
  return path.replace(/\\/g, '/'); // 将反斜杠替换为斜杠
};


// 加载菜品列表
const fetchDishes = async () => {
  if(loading.value) return;
  loading.value = true
  try {
    const params = {
      pageNo: currentPage.value,
      pageSize: pageSize.value,
      name: searchQuery.value,
      categoryId: selectedCategory.value
    }

    const res = await getDishList(params)
    await new Promise(resolve => setTimeout(resolve, 300)) // 模拟延迟
    if (res.code === '200') {
      dishList.value = res.data.records
      total.value = res.data.total
    }else{
      ElMessage.error(res.msg || '获取菜品列表失败')
    }
  } catch (error) {
    ElMessage.error('获取菜品列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1
  fetchDishes()
}

// 分类筛选变化
const handleCategoryChange = () => {
  currentPage.value = 1
  fetchDishes()
}

// 多选处理
const handleSelectionChange = (selection) => {
  selectedDishes.value = selection.map(item => item.id)
}

// 批量删除
const batchDelete = () => {
  ElMessageBox.confirm('确定要删除选中的菜品吗?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    console.log("select-id=",selectedDishes.value)
    const submitDeleteIds = {
      ids:selectedDishes.value
    }
    const res = await deleteDishes(submitDeleteIds)
    if (res.code === '200') {
      ElMessage.success(`成功删除${selectedDishes.value.length}项`)
      selectedDishes.value = []
      await fetchDishes()
    }else{
      ElMessage.error(res.msg || '删除失败')
    }
  }).catch(() => {})
}

// 批量更新状态
const batchUpdateStatus = async (status) => {
  try {
    const submitFormData = {
      ids:selectedDishes.value,
      status:status
    }
    const res = await updateBatchStatus(submitFormData)

    if (res.code === '200') {
      ElMessage.success(status === 1 ? '已批量起售' : '已批量停售')
      await fetchDishes()
      selectedDishes.value = []
    }else{
      ElMessage.error(res.msg || '操作失败')
    }
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

// 单个菜品状态切换
const toggleStatus = async (row) => {
  const newStatus = row.status === 1 ? 0 : 1
  try {
    const submitFormData = {
      ids:[row.id],
      status:newStatus
    }
    const res = await updateBatchStatus(submitFormData)
    if (res.code === '200') {
      ElMessage.success(newStatus === 1 ? '已起售' : '已停售')
      await fetchDishes()
    }else{
      ElMessage.error( '操作失败')
    }
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

// 单个删除
const handleDelete = (id) => {
  ElMessageBox.confirm('确定要删除该菜品吗?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    const res = await deleteDishById(id);
    if (res.code === '200') {
      ElMessage.success(res.data||'删除成功')
      await fetchDishes()
    }else {
      ElMessage.error(res.msg || '删除失败')
    }
  }).catch(() => {})
}

// 导航到添加页面
const navigateToAddDish = () => {
  router.push('/dish/add')
}

// 导航到编辑页面
const navigateToEditDish = (id) => {
  router.push(`/dish/edit/${id}`)
}

// 分页处理函数
const handlePageChange = (newPage) => {
  currentPage.value = newPage;
  fetchDishes()
};
const handlePageSizeChange = (newSize) => {
  pageSize.value = newSize;
  currentPage.value = 1; // 必须重置页码
  fetchDishes()
};

// 初始化加载
onMounted(async () => {
  await fetchDishes()
  await loadDishCategories()
})
</script>

<style scoped>
.dish-management {
  padding: 20px;
}

.search-bar {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.search-left {
  display: flex;
}

.search-right {
  display: flex;
  gap: 10px;
}


.el-image {
  cursor: pointer;
  transition: transform 0.3s;
}

.el-image:hover {
  transform: scale(1.05);
}
</style>